namespace Vuscode.FNHSamples.WebApp
{
    using Domain;

    using FluentNHibernate.Automapping;
    using FluentNHibernate.Cfg;
    using FluentNHibernate.Cfg.Db;

    using Framework.NHibernate.Conventions;

    using NHibernate;

    /// <summary>
    /// Configure NHibernate Mercury Session factory
    /// </summary>
    public class NHIbernateBootstrapper
    {
        /// <summary>
        /// Init the session factory.
        /// </summary>
        /// <returns>Initialized NHibernate configuration.</returns>
        public static void InitializeNHibernateMappings(bool shouldCreateDBEntities)
        {
            var persistenceModel = AutoMap.AssemblyOf<BlogRoll>()
                .Conventions.AddFromAssemblyOf<ClassConvention>()
                .Setup(s =>
                    {
                        s.SubclassStrategy = t => SubclassStrategy.JoinedSubclass;
                        s.IsComponentType = type => type == typeof(Address);
                    })
                .IgnoreBase<Entity>()
                .IncludeBase<Author>()
                .Where(t => !t.Name.EndsWith("Repository") &&
                            !t.Name.EndsWith("Service") &&
                            !t.Name.EndsWith("Bootstrapper")
                );
            var cfg = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005.ConnectionString(p => p.FromConnectionStringWithKey("FNHSample")))
                .Mappings(m => m.AutoMappings.Add(persistenceModel))
                .BuildConfiguration();

            if (shouldCreateDBEntities)
            {
                new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Execute(true, true, false);
                // next line is just for checking how the nhibernate xml configuration files look
                persistenceModel.WriteMappingsTo(@"C:\Temp");
            }

            var sessionFactory = cfg.BuildSessionFactory();

            // IoC.Register(sessionFactory);
        }
    }
}